package com.ice.framework.web.validator;

import com.ice.framework.common.base.BaseEnum;
import lombok.NonNull;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * @author wangwei
 * @Date 2023/11/9 14:22
 */
public class SelfEnumValidator implements ConstraintValidator<EnumValid, Object> {

    private Class<? extends BaseEnum> enumClass = null;

    @Override
    public void initialize(EnumValid enumValue) {
        enumClass = enumValue.enumClass();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
        if (value == null) {
            return Boolean.FALSE;
        }
        try {
            BaseEnum result = off(enumClass, String.valueOf(value));
            return result != null;
        } catch (Exception e) {
            e.printStackTrace();
            return Boolean.FALSE;
        }
    }

    public static <E extends BaseEnum> E off(@NonNull Class<E> classType, String value) {
        for (E enumConstant : classType.getEnumConstants()) {
            if (enumConstant.getCode().equals(value)) {
                return enumConstant;
            }
        }
        return null;
    }
}
